package com.fingard.dsp.bank.directbank.gfgs01;

import java.io.File;
import java.sql.Connection;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;

/**
 * 东航物流电子回单
 */
public class GFGS01Receipt extends GFGS01Base implements IReceipt{
    //交易传入的数据
    private String receiptSaveToMainDir = "";

    private static final String INSERTRECEIPT = "INSERT INTO RECEIPTMAPPING(URID,BANK,OWNACT,BUSDATE,RECEIPTNO,RECEIPTFILE,CREATEDON) values (?,?,?,?,?,?,?);";
    private static final String SELECTRECEIPT = "SELECT RECEIPTFILE FROM RECEIPTMAPPING WHERE BANK=? AND OWNACT=? AND BUSDATE=? AND RECEIPTNO=?;";

    public RetAtsReceipt qryReceipt(final ReqQryReceipt p_reqReceipt) throws Exception {
        //回单查询返回ATS的对象
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
        if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
            if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                    download(p_reqReceipt);
                    retAts.respInfo = "后台处理中";
                    retAts.respCode = "0";
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件共享目录";
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public void download(ReqQryReceipt p_reqReceipt) throws Exception{
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        //回单查询返回ATS的对象
        Connection conn = FGBiz.getLocalDbConn();
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            //返回到ATS的请求String
            StringBuilder json = new StringBuilder("transType=downloadreceipt&data={\"rows\":[");
            int tmpFileCount = 0;//记录上传成功的回单数
            StringBuilder sb = new StringBuilder();
            //按天查询
            while (tmpIntFrom <= tmpIntTo) {
                Date fromDateStep = tmpCalendarFrom.getTime();
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));

                //本地存放回单目录
                String localFilePath=FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "datafile" + File.separator + bankFront.code
                        + File.separator + "receiptDataFile" + File.separator + Format.Date8Format.format(fromDateStep);
                if(!FileHelper.existFile(localFilePath)){
                    FileHelper.mkdir(localFilePath);
                }
                //1、查询当前时间的明细流水，匹配流水号，账号，只下载有明细流水的电子回单
                String receiptString=selectReceipt(p_reqReceipt.actNum,Format.Date8Format.format(fromDateStep));
                if(StringHelper.hasAnyChar(receiptString)){
                    //2、开始循环上传到共享目录，只上传可查询到明细的回单文件
                    String[] receiptArray=receiptString.replaceAll(" ","").split("#");//查询到明细的流水串
                    for(int i=0;i<receiptArray.length;i++){
                        //明细流水号|交易额|交易方向|对方账号|对方户名|
                        String[] receiptContent=receiptArray[i].split("\\|");
                        if(receiptContent.length==5){
                            //2.1 防重操作：查询已上传共享目录文件
                            Map<String, Object>  tabMap = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{reqHeader.bankCode, p_reqReceipt.actNum, Integer.parseInt(Format.Date8Format.format(fromDateStep)), receiptContent[0]});
                            if (tabMap != null && tabMap.size() > 0 && tabMap.containsKey("RECEIPTFILE")) {
                                WriteBankLogLn("回单编号"+receiptContent[0]+"已下载成功/上传成功,不再重复上传");
                                continue;
                            }
                            //2.2、开始从ftp服务器上下载电子回单
                            FtpSet ftpSet = bankFront.getFtpSet("receipt");
                            downFromFtp(localFilePath,ftpSet,receiptContent[0],Format.Date8Format.format(fromDateStep));
                            //2.3 开始上传回单文件到共享目录下
                            String receiptPath=localFilePath+"/"+receiptContent[0]+".pdf";//回单文件路径
                            File receiptFile=new File(receiptPath);
                            if(receiptFile!=null){
                                //回单存放共享目录路径
                                String tmpByDate = Format.Date8Format.format(new Date());
                                tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/" + receiptFile.getName().substring(4,12) + "/";
                                //2.3.1、上传文件到共享目录下
                                int result = -1;
                                WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                if (receiptFile.exists()) {
                                    result = SmbFileUtil.smbUploading(receiptFile.getPath(), tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                }
                                //2.3.2、上传成功处理
                                if (result == 0 || result == 1) {
                                    //记录上传成功数
                                    tmpFileCount++;
                                    if (result == 0) {
                                        WriteBankLogLn("文件上传成功");
                                    }else {
                                        WriteBankLogLn("文件已存在共享目录无需重复上传");
                                    }
                                    //推送数据给ATS处理
                                    json.append("{");
                                    json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                    json.append("\"actCur\":\""+ getBankConfig().getMapKeyByValue("curActMapping",p_reqReceipt.actNum) +"\",");
                                    json.append("\"receiptCode\":\"" + receiptContent[0] + "\",");//回单编号
                                    json.append("\"receiptType\":\"" + "" + "\",");//回单类型  1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                    json.append("\"receiptState\":\"" + "" + "\",");//回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                    json.append("\"oppActName\":\"" + receiptContent[4] + "\",");
                                    json.append("\"oppActNum\":\"" + receiptContent[3] + "\",");
                                    json.append("\"amount\":\"" + receiptContent[1] + "\",");
                                    json.append("\"moneyway\":\"" + receiptContent[2] + "\",");
                                    json.append("\"tranSeqNo\":\"" + receiptContent[0] + "\",");
                                    json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                    json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(receiptFile.getName().substring(4,12))) + "\",");
                                    json.append("\"filePath\":\"" + tmpByDate + receiptFile.getName() + "\",");//回单文件仓库存储路径
                                    json.append("\"fileType\":\"1\"");
                                    json.append("},");
                                    sb.append(receiptFile.getName()+",");
                                    //2.3.3、记录已推送的电子回单
                                    JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{UUID.randomUUID().toString(), reqHeader.bankCode, p_reqReceipt.actNum, receiptFile.getName().substring(4,12),receiptContent[0], receiptFile.getPath(), new Date()});
                                } else {
                                    WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                    continue;
                                }
                            }
                        }
                    }
                }else {
                    WriteBankLogLn("账号"+p_reqReceipt.actNum+"在"+Format.Date8Format.format(fromDateStep)+"不存在明细流水，不需要下载");
                }
            }
            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件,文件名为："+sb);
            //3、上传共享目录成功数据推送到ats
            if (tmpFileCount > 0) {
                json.deleteCharAt(json.length() - 1);
                json.append("]}");
                WriteBankLogLn("推送数据到ATS的数据为：" + json.toString());
                String[] data = sendToATS(json.toString());
                if (data[0].length() == 0 && data[1].equals("ok")) {
                    WriteBankLogLn("推送数据到ATS成功,请查看数据");
                } else {
                    WriteBankLogLn("推送数据到ATS失败");
                }
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }
        } catch (Exception e) {
            WriteBankLogLn("东航物流电子回单异常："+e.getMessage());
            e.printStackTrace();
        } finally {
            conn.close();
        }
        retAts.writeRetToATS();
    }
}
